var textfieldTemplate = "<label>{0}</label>:<br/><input class=\"save\" id=\"{0}\" type=\"text\" name=\"{0}\" value=\"{1}\"><span warning=\"{0}\" class=\"warning\"></span><br/><br/>";
var selectTemplate = "<label>{0}</label>:<br/><select class=\"save\" id=\"{1}\">{2}</select><br/><br/>";
var optionTemplate = "<option value='{0}'{2}>{1}</option>";

String.format = function() {
	  var s = arguments[0];
	  for (var i = 0; i < arguments.length - 1; i++) {       
	    var reg = new RegExp("\\{" + i + "\\}", "gm");             
	    s = s.replace(reg, arguments[i + 1]);
	  }
	  return s;
}

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

function buildFormForNew(documentData){
	buildForm(documentData, true);
}

function buildFormForCreated(documentData){
	buildForm(documentData, false);
}

function buildForm(documentData, isNew) {
	console.log(documentData);

	$('#form_wrapper').removeClass('hidden');
	
	var attributesHtml = '';
	/*for every json-object*/
	for(var i = 0; i < documentData.length; i = i+1) {
		
		/*if current json-object is a set of standard attributes, set these attributes*/

		if(documentData[i].dataType=="common") {
			//set all common fields	
			$("#type").text(documentData[i].docType);
			$("#id").val(documentData[i].id);
			$("#description").val(documentData[i].description);
			$("#name").val(documentData[i].name);
			$("#status").children().each(function() {
			    if($(this).attr("value")==documentData[i].status) {
			    	$(this).attr('selected','');
			    };
			});	
			
		/*if current json-object is a single attribute, generate and append an attribute*/	
		} else {
			/*attribute is a text field*/		
			if(documentData[i].type=="textfield") {	
				if(documentData[i].value==null){
					documentData[i].value = "";
				}
				attributesHtml += String.format(textfieldTemplate, documentData[i].lable, documentData[i].value);
				
			/*attribute is a date*/		
			} else if(documentData[i].type=="date") {	
				if(documentData[i].value==null){
					documentData[i].value = "";
				}
				attributesHtml += String.format(textfieldTemplate, documentData[i].lable, documentData[i].value);
				
			/*attribute is a dropdown-list*/			
			} else if(documentData[i].type=="select") {
				var options = ""
				for(var j = 0; j < documentData[i].values.length; j++) {
					
					var value = documentData[i].values[j].value;
					var selected = ""
					if(documentData[i].values[j].value == documentData[i].value) {
						selected = " selected ";
					}
					options += String.format(optionTemplate, documentData[i].values[j].value, documentData[i].values[j].text, selected);
				}
				attributesHtml += String.format(selectTemplate, documentData[i].lable, documentData[i].lable, options);
			}					
		}
	}
	$('#attributes').html(attributesHtml);
	if(isNew) {
		setSaveNewDocMode();
	} else {
		setUpdateThisDocMode();
	}
	
}

/* ---------SAVE & UPDATE----------- */

function saveDocument() {
	var url = "saveDocumentJson";
	
	var data = {};
	$('.save').each(function() {
		data[$(this).attr('id')] = $(this).val();
	});
	data["catalog"] = getURLParameter("catalog");
	
	$.get(
		url, 
		data,
		processAndShowErrors,
		"json"
	);
}

function setSaveNewDocMode() {
	$("#saveNewDocButton").show();
	$("#updateThisDocButton").hide();
}
function setUpdateThisDocMode() {
	$("#saveNewDocButton").hide();
	$("#updateThisDocButton").show();
}

function clearAllValidationFeedback() {
	$(".success, .not_saved_warning").hide();
	$(".warning").each(function() {
		$(this).html("");
	});
}

function clearAllInputFields() {
	$("input").each(function() {
		$(this).val("");
	});
}

function processAndShowErrors(errors) {
	//console.log(errors);
	if(errors.status=="success") {  /*FIREBUG*/
		$(".success").show();
	} else {
		$(".not_saved_warning").show();
		for(var prop in errors.errors) {
			$('.warning[warning="' + prop + '"]').html(errors.errors[prop]);
		}
		
	}
}

/* ---------------------------------------------- */

$(document).ready(function () {
	$(".success, .not_saved_warning").hide();
	
	$('.link_to_document').click(function() {
		clearAllValidationFeedback();
		var url = "documentFormJson";
		var docId = $(this).attr('docId');
		console.log(url);
		$.get(
			url, 
			{ "id": docId},
			buildFormForCreated,
			"json"
		);
	});
	
	$("#add_new_doc_button").click(function () {
		clearAllInputFields();
		clearAllValidationFeedback();
		var type = $('#docType').val();
		var url = "documentFormJson";
		console.log(url);
		$.get(
			url, 
			{ 
				"id": "new",
				"doc_type" : type
			},
			buildFormForNew,
			"json"
		);
	});

	$("#saveNewDocButton, #updateThisDocButton").click(function (e) {
		e.preventDefault();
		var errors = saveDocument();
		clearAllValidationFeedback();
		processAndShowErrors(errors);
	});
	
	
	//fillStatusSelect:
	var template = "";
	var statusContent = "";
	for(var i = 0; i < availableStatuses.length; i = i+1) {
		statusContent += String.format(optionTemplate, availableStatuses[i].value, availableStatuses[i].text, "")
	}
	$("#status").append(statusContent);
	
	$('.clipboardButton').click(function(){
		$button = $(this);
		var docId = $button.attr('id');
		
		$.get(
				"addToClipboard", 
				{ "id": docId},
				function(data) {
					//$button.remove();
					alert('document added to clipboard');
				},
				"json"
		);
	});
	
	$('#paste').click(function(){
		var catalog = getURLParameter("catalog");
		window.location = "documentView?catalog="+catalog+"&paste=true";
	});
	
	
	
});